#include "head.h"

// 工作线程用来读取main线程accept的客户端连接对象
// 参数一: 工进程程用来和main进程通信的特制本地socket
// 参数二: 用来存储从本地socket中读到的客户端连接对象的文件描述符
int readNetFd(int SonFd, int *NetFd){

   struct msghdr hdr;
   bzero(&hdr, sizeof(hdr));

   struct iovec vec[1];
   int flag = 1;
   vec[0].iov_base = &flag;
   vec[0].iov_len = sizeof(int);

   hdr.msg_iov = vec;
   hdr.msg_iovlen = 1;

   struct cmsghdr *pcmsg = 
       (struct cmsghdr *)malloc(
                       CMSG_LEN(sizeof(int)));
   pcmsg->cmsg_len = CMSG_LEN(sizeof(int));
   pcmsg->cmsg_level = SOL_SOCKET;
   pcmsg->cmsg_type = SCM_RIGHTS;

   hdr.msg_control = pcmsg;
   hdr.msg_controllen = CMSG_LEN(sizeof(int));

   int ret = recvmsg(SonFd, &hdr, 0);
   ERROR_CHECK(ret, -1, "recvmsg");

   void *addr = CMSG_DATA(pcmsg);
   int *p_fd = (int *)addr;
   *NetFd = *p_fd;

   return 0;
}

// main进程accept获得的客户端连接对象发送给工作进程
// 参数一: main进程用来和工作进程通信的本地socket
// 参数二: main进程accept获得到的客户端连接文件对象的文件描述符
int copyNetFd(int* NetFd,int fd){
    
    printf("star copyNetFd\n");

   struct msghdr hdr;
   bzero(&hdr, sizeof(hdr));

   struct iovec vec[1];
   int flag = 1;
   vec[0].iov_base = &flag;
   vec[0].iov_len = sizeof(int);

   hdr.msg_iov = vec;
   hdr.msg_iovlen = 1;

   struct cmsghdr *pcmsg = 
       (struct cmsghdr *)malloc(
                       CMSG_LEN(sizeof(int)));
   pcmsg->cmsg_len = CMSG_LEN(sizeof(int));
   pcmsg->cmsg_level = SOL_SOCKET;
   pcmsg->cmsg_type = SCM_RIGHTS;

   void *addr = CMSG_DATA(pcmsg);
   int *p_int = (int *)addr;
   *p_int = *NetFd;

   hdr.msg_control = pcmsg;
   hdr.msg_controllen = CMSG_LEN(sizeof(int));

   int ret = sendmsg(fd, &hdr, 0);
   ERROR_CHECK(ret, -1, "sendmsg");

    printf("end copyNetFd!\n");

   return 0;
}
